package com.github.chirspan.xaas.rbac.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.chirspan.xaas.mybatis.service.impl.BaseServiceImpl;
import com.github.chirspan.xaas.mybatis.util.tree.TreeUtils;
import com.github.chirspan.xaas.rbac.dao.RbacResourceDao;
import com.github.chirspan.xaas.rbac.model.RbacResource;
import com.github.chirspan.xaas.rbac.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * ************************
 * <p></p>
 * *************************
 *
 * @author chenpan
 * @date 2021/1/19 16:29
 */
@Service
public class ResourceServiceImpl extends BaseServiceImpl<RbacResourceDao, RbacResource> implements IResourceService {

    @Autowired
    private RbacResourceDao resourceDao;

    @Override
    @Cacheable(value = "permission", key = "'user_'.concat(#p0)", unless = "#result == null || #result.size() == 0")
    public Set<String> getStringPermissions(String username) {
        List<RbacResource> permissionList = resourceDao.findUserPermissions(username);
        Set<String> permissionSet = new HashSet<>();
        if (permissionList != null) {
            for (RbacResource r : permissionList) {
                if (StrUtil.isNotBlank(r.getPermission())) {
                    permissionSet.add(r.getPermission());
                }
            }
        }
        return permissionSet;
    }

    @Override
    public List<RbacResource> findResourcesTree(RbacResource resource) {
        return TreeUtils.buildTree(resourceDao.findResources(resource));
    }

    @Override
    @Cacheable(value = "resource:tree", key = "'user_'.concat(#p0)+'_'+#p1.toString()"
            , unless = "#result == null || #result.size() == 0")
    public List<RbacResource> findUserSysResources(String username, List<String> appIds) {
        return TreeUtils.buildTree(resourceDao.findUserMenus(username, appIds));
    }
}
